package config

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
	"userServer/model"
)

var (
	DB *gorm.DB
)

func InitDB() error {
	var err error
	DB, err = initMysql()
	return err
}

func initMysql() (*gorm.DB, error) {
	host := viper.GetString("database.host")
	port := viper.GetInt("database.port")
	user := viper.GetString("database.user")
	pass := viper.GetString("database.password")
	name := viper.GetString("database.name")
	charset := viper.GetString("database.charset")
	loc := viper.GetString("database.loc")
	parseTime := viper.GetBool("database.parse_time")

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=%t&loc=%s",
		user, pass, host, port, name, charset, parseTime, loc,
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("连接数据库失败：" + err.Error())
	}

	err = db.AutoMigrate(&model.User{})

	// 连接池配置
	sqlDB, err := db.DB()
	if err != nil {
		return nil, fmt.Errorf("获取底层数据库连接失败: %w", err)
	}

	sqlDB.SetMaxIdleConns(viper.GetInt("database.max_idle_conns"))
	sqlDB.SetMaxOpenConns(viper.GetInt("database.max_open_conns"))
	sqlDB.SetConnMaxLifetime(time.Duration(viper.GetInt("database.conn_max_lifetime")) * time.Second)

	if db == nil {
		fmt.Println("MySQL 连接失败！", err)
		return nil, err
	}
	fmt.Println("MySQL 连接成功！")

	return db, nil
}
